import pickle
import io
import base64
import time
import os
from apps.crm.models import UseNumber, Order
from application import db, app, mail, redis
from apps.crm.models import Order
from celery import Celery
from libs import itchat
from eventlet import GreenPool, sleep
from flask_mail import Message
from flask import render_template_string
from wxpy import Group, Bot


def make_celery(app):

    celery = Celery(
        backend=app.config['CELERY_RESULT_BACKEND'],
        broker=app.config['CELERY_BROKER_URL']
    )
    celery.conf.update(app.config)

    class ContextTask(celery.Task):
        def __call__(self, *args, **kwargs):
            with app.app_context():
                return self.run(*args, **kwargs)

    celery.Task = ContextTask
    return celery


celery_in = make_celery(app=app)


@celery_in.task
def SendMessage(chat, card_number):
    card = db.session.query(UseNumber).filter(
        UseNumber.card_number == card_number).first()
    if not card or card.is_use:
        return
    status = base64.b64decode(chat)
    status = pickle.loads(status)
    user = status['loginInfo'].get('User')
    chat = itchat.new_instance()
    chat.load_login_status(status)
    chat.web_init()
    number = 0
    friends = chat.get_friends(update=True)
    start = time.time()
    chat.send(u'您好，欢迎使用我们的群发消息版', 'filehelper')
    chat.send(u'在此发送您的消息，此后这条消息将会被群发', 'filehelper')
    chat.send(u'剩余发送消息有效期时间 120s', 'filehelper')
    
    while True:
        try:
            message = chat.msgList.get(timeout=1)
        except Exception as e:
            if (time.time() - start) % 10 < 1:
                chat.send(u'剩余发送消息有效期时间 %ss'%(int(time.time())), 'filehelper')
            if time.time() - start > 120:
                return
        
        else:
            if message['ToUserName'] == 'filehelper':
                msgType = message['MsgType']
                content = message['Content']
                break

    for i in friends:
        res = chat.send_raw_msg(msgType, content, i['UserName'])
        time.sleep(app.config['SEND_TIME_SPACE'])

    card.is_use=True
    db.session.commit()
    chat.send(u'群发完毕', 'filehelper')
    chat.logout()



@celery_in.task
def freeClear(chat,card_number):
 
    status = base64.b64decode(chat)
    status = pickle.loads(status)
    user = status['loginInfo'].get('User')
    chat = itchat.new_instance()
    chat.load_login_status(status)
    chat.web_init()
    chat.send(u'您好，欢迎使用我们的免费版', 'filehelper')
    friends = chat.get_friends(update=True)
    f = friends[1:]
    chat.send('检测到 %s 位好友' % (len(f)), 'filehelper')
    redis.lpush(card_number, pickle.dumps(['检测到 %s 位好友' % (len(f)),None]))
    f = friends[:101]
    res=chat.search_chatrooms('qinghaoyou______2_______')
    for i in res:
        print(i)
    ret=[]  # 检测后的好友
    # ----------------------------
    start=0
    # ------------------------------
    for i in range(10, len(f), 50):
        check=f[start:i]
        if res:
            group=chat.add_member_into_chatroom('qinghaoyou______2_______', check)
        else:
            group=chat.create_chatroom(check, 'qinghaoyou______2_______')
        print(group)
        for j in group['MemberList']:

            current=filter(lambda x: x['UserName'] == j['UserName'], check)
            j.update(next(current))
            content_header = 'data:image/jpg;base64,'
            content = base64.b64encode(chat.get_head_img(j['UserName'])).decode('utf-8')
            j.update({'HeadImgUrl':content_header + content})
            ret.append(j)
        start=i
        chat.send('加载了 %s 位好友' %
                  (len(friends) if i > len(f) else i), 'filehelper')
        redis.lpush(card_number, pickle.dumps(['加载了 %s 位好友' %
                    (len(friends) if i > len(f) else i),None]))
        time.sleep(3)
    delete=[]  # 被删除
    black=[]  # 黑名单
    for i in ret:

        if i['MemberStatus'] == 4:
            delete.append(i)
            chat.send('%s 将您删除' % (i['NickName']), 'filehelper')
            redis.lpush(card_number,pickle.dumps([ '%s 将您删除' % (i['NickName']),i]))
            chat.send_raw_msg(itchat.content.TEXT, '清理好友，误回', i['UserName'])
        elif i['MemberStatus'] == 3:
            black.append(i)
            chat.send('%s 将您拉黑' % (i['NickName']), 'filehelper')
            redis.lpush(card_number, pickle.dumps(['%s 将您拉黑' % (i['NickName']),i]))

            chat.send_raw_msg(itchat.content.TEXT, '清理好友，误回', i['UserName'])
    chat.send('被拉黑  %s\n被删除 %s' % (len(black), len(delete)), 'filehelper')
    redis.lpush(card_number, pickle.dumps(['被拉黑  %s\n被删除 %s' % (len(black), len(delete)), 'done']))
    chat.logout()

  


@celery_in.task
def clear_friends(chat, card_number):
    card = db.session.query(UseNumber).filter(
        UseNumber.card_number == card_number).first()
    if not card or card.is_use:
        return
    status = base64.b64decode(chat)
    status = pickle.loads(status)
    user = status['loginInfo'].get('User')
    chat = itchat.new_instance()
    chat.load_login_status(status)
    chat.web_init()
    chat.send(u'您好，欢迎使用我们的产品', 'filehelper')
    friends = chat.get_friends(update=True)
    f = friends[1:]
    chat.send('检测到 %s 位好友' % (len(f)), 'filehelper')
    redis.lpush(card_number, pickle.dumps(['检测到 %s 位好友' % (len(f)),None]))
    f = friends[1:card.Order2Product.product.f_limit]

    ret=[]  # 检测后的好友
    # ----------------------------
    start=0
    # ------------------------------
    for i in range(10, len(f), 20):
        check=f[start:i]
        
        
        group=chat.create_chatroom(check, '___%s'%(int(time.time())))
        print(group)
        for j in group['MemberList']:

            current=filter(lambda x: x['UserName'] == j['UserName'], check)
            j.update(next(current))
            content_header = 'data:image/jpg;base64,'
            content = base64.b64encode(chat.get_head_img(j['UserName'])).decode('utf-8')
            j.update({'HeadImgUrl':content_header + content})
            ret.append(j)
        start=i
        chat.send('加载了 %s 位好友' %
                  (len(friends) if i > len(f) else i), 'filehelper')
        redis.lpush(card_number, pickle.dumps(['加载了 %s 位好友' %
                    (len(friends) if i > len(f) else i),None]))
        time.sleep(3)
    delete=[]  # 被删除
    black=[]  # 黑名单
    for i in ret:

        if i['MemberStatus'] == 4:
            delete.append(i)
            chat.send('%s 将您删除' % (i['NickName']), 'filehelper')
            redis.lpush(card_number,pickle.dumps([ '%s 将您删除' % (i['NickName']),i]))
            chat.send_raw_msg(itchat.content.TEXT, '清理好友，误回', i['UserName'])
        elif i['MemberStatus'] == 3:
            black.append(i)
            chat.send('%s 将您拉黑' % (i['NickName']), 'filehelper')
            redis.lpush(card_number, pickle.dumps(['%s 将您拉黑' % (i['NickName']),i]))

            chat.send_raw_msg(itchat.content.TEXT, '清理好友，误回', i['UserName'])
    chat.send('被拉黑  %s\n被删除 %s' % (len(black), len(delete)), 'filehelper')
    redis.lpush(card_number, pickle.dumps(['被拉黑  %s\n被删除 %s' % (len(black), len(delete)), 'done']))
    chat.logout()
    card.is_use=True
    db.session.commit()



@celery_in.task
def clear_friends_black(chat, card_number):
    card = db.session.query(UseNumber).filter(
        UseNumber.card_number == card_number).first()
    if not card or card.is_use:
        return
    status = base64.b64decode(chat)
    status = pickle.loads(status)
    user = status['loginInfo'].get('User')
    chat = itchat.new_instance()
    chat.load_login_status(status)
    chat.web_init()
    chat.send(u'您好，欢迎使用我们的产品', 'filehelper')
    friends = chat.get_friends(update=True)
    f = friends[1:]
    chat.send('检测到 %s 位好友' % (len(f)), 'filehelper')
    redis.lpush(card_number, pickle.dumps(['检测到 %s 位好友' % (len(f)),None]))
    f = friends[1:card.Order2Product.product.f_limit]
    res=chat.search_chatrooms('qinghaoyou______2_______')
    for i in res:
        print(i)
    ret=[]  # 检测后的好友
    # ----------------------------
    start=0
    # ------------------------------
    for i in range(10, len(f), 20):
        check=f[start:i]
        if res:
            group=chat.add_member_into_chatroom('qinghaoyou______2_______', check)
        else:
            group=chat.create_chatroom(check, 'qinghaoyou______2_______')
        print(group)
        for j in group['MemberList']:

            current=filter(lambda x: x['UserName'] == j['UserName'], check)
            j.update(next(current))
            content_header = 'data:image/jpg;base64,'
            content = base64.b64encode(chat.get_head_img(j['UserName'])).decode('utf-8')
            j.update({'HeadImgUrl':content_header + content})
            ret.append(j)
            ret.append(j)

        start=i
        chat.send('加载了 %s 位好友' %
                  (len(friends) if i > len(f) else i), 'filehelper')
        redis.lpush(card_number, pickle.dumps(['加载了 %s 位好友' %
                    (len(friends) if i > len(f) else i),None]))
        time.sleep(5)
    black=[]  # 黑名单
    for i in ret:

        if i['MemberStatus'] == 3:
            black.append(i)
            chat.send('%s 将您拉黑' % (i['NickName']), 'filehelper')
            redis.lpush(card_number, pickle.dumps(['%s 将您拉黑' % (i['NickName']),i]))
        
    chat.send('被拉黑  %s' % (len(black)), 'filehelper')
    redis.lpush(card_number, pickle.dumps(['被拉黑  %s' % (len(black)), 'done']))
    chat.logout()
    card.is_use=True
    db.session.commit()


@celery_in.task
def clear_friends_delete(chat, card_number):
    card = db.session.query(UseNumber).filter(
        UseNumber.card_number == card_number).first()
    if not card or card.is_use:
        return
    status = base64.b64decode(chat)
    status = pickle.loads(status)
    user = status['loginInfo'].get('User')
    chat = itchat.new_instance()
    chat.load_login_status(status)
    chat.web_init()
    chat.send(u'您好，欢迎使用我们的产品', 'filehelper')
    friends = chat.get_friends(update=True)
    f = friends[1:]
    chat.send('检测到 %s 位好友' % (len(f)), 'filehelper')
    redis.lpush(card_number, pickle.dumps(['检测到 %s 位好友' % (len(f)),None]))
    f = friends[1:card.Order2Product.product.f_limit]
    res=chat.search_chatrooms('qinghaoyou______2_______')
    for i in res:
        print(i)
    ret=[]  # 检测后的好友
    # ----------------------------
    start=0
    # ------------------------------
    for i in range(10, len(f), 50):
        check=f[start:i]
        if res:
            group=chat.add_member_into_chatroom('qinghaoyou______2_______', check)
        else:
            group=chat.create_chatroom(check, 'qinghaoyou______2_______')
        print(group)
        for j in group['MemberList']:

            current=filter(lambda x: x['UserName'] == j['UserName'], check)
            j.update(next(current))
            content_header = 'data:image/jpg;base64,'
            content = base64.b64encode(chat.get_head_img(j['UserName'])).decode('utf-8')
            j.update({'HeadImgUrl':content_header + content})
            ret.append(j)
            ret.append(j)
        start=i
        chat.send('加载了 %s 位好友' %
                  (len(friends) if i > len(f) else i), 'filehelper')
        redis.lpush(card_number, pickle.dumps(['加载了 %s 位好友' %
                    (len(friends) if i > len(f) else i),None]))
        time.sleep(3)
    delete=[]  # 被删除
    for i in ret:

        if i['MemberStatus'] == 4:
            delete.append(i)
            chat.send('%s 将您删除' % (i['NickName']), 'filehelper')
            redis.lpush(card_number,pickle.dumps([ '%s 将您删除' % (i['NickName']),i]))
            chat.send_raw_msg(itchat.content.TEXT, '清理好友，误回', i['UserName'])
    chat.send('被删除 %s' % (len(delete)), 'filehelper')
    redis.lpush(card_number, pickle.dumps(['被删除 %s' % ( len(delete)), 'done']))
    chat.logout()
    card.is_use=True
    db.session.commit()


@celery_in.task
def send_email(order):
    order=db.session.query(Order).filter(Order.id == order).first()


    with open(os.path.join(app.config['BASE'], 'templates', 'email.html')) as f:
        email_str=f.read()


    with mail.connect() as conn:
        for i in order.products:
            for useNumber in i.usenumber:
                print(useNumber, i.email)
                msg=Message(
                    '激活信息',
                    sender=app.config['MAIL_USERNAME'],
                    recipients=[i.email])
                msg.body='您的激活卡为 %s 仅能使用一次,请勿借给他人' % (useNumber.card_number)
                msg.html=render_template_string(
                    email_str,
                    href="%s%s" % (
                        app.config['DOMAIN'], '/#/checked/index/?card_number=%s' % (useNumber.card_number)),
                    id=useNumber.card_number
                ).replace('\t', '').replace('\r\n', '')
                useNumber.is_use=False
                conn.send(msg)

    db.session.commit()


@celery_in.task
def send_email_register(email_addr,url):

    with mail.connect() as conn:
        
        msg=Message(
            '点卡信息',
            sender=app.config['MAIL_USERNAME'],
            recipients=[email_addr])

        msg.body='您的激活地址为 %s ' % (url)
        
        conn.send(msg)